/*
 * @Description:
 * @Author: Mr.Wen
 * @Version: v1.0.0
 * @Date: 2022-08-23 14:28:22
 * @LastEditors: Mr.Wen - 文先生
 * @LastEditTime: 2023-12-28 14:39:49
 */

'use strict';

const os = require('os');
const fs = require('fs');

/**
 * 获取当前机器 IP 地址
 * @returns '127.0.0.1'
 */
module.exports.GetAdressIP = function GetAdressIP() {
  const interfaces = os.networkInterfaces();
  const localInfo = interfaces['WLAN'].find((v) => v.family === 'IPv4');
  return localInfo.address;
};

/**
 * 读写文件操作
 * @param { String } url 存储文件路径
 * @param { * } body 内容
 * @returns
 */
module.exports.Read2WriteFile = (url, body) => {
  return new Promise((resolve, reject) => {
    fs.readFile(url, 'utf-8', (error, data) => {
      if (!error) {
        // TODO 读取文件成功
        if (!data) {
          // TODO 判断是否第一次写入
          const newArray = [];
          newArray.push(body);
          fs.writeFile(url, JSON.stringify(newArray, null, 2), (error) => {
            if (!error) {
              resolve('写入成功');
            } else {
              reject('写入失败');
            }
          });
        } else {
          const newData = JSON.parse(data);
          newData.push(body);
          fs.writeFile(url, JSON.stringify(newData, null, 2), (error) => {
            if (!error) {
              resolve('写入成功');
            } else {
              reject('写入失败');
            }
          });
        }
      } else {
        reject('读取失败');
      }
    });
  });
};

/**
 * 读取文件操作
 * @param { String } url 存储文件路径
 * @returns
 */
module.exports.ReadFile = (url) => {
  return new Promise((resolve, reject) => {
    fs.readFile(url, 'utf-8', (error, data) => {
      if (!error && data) {
        resolve(JSON.parse(data));
      } else {
        reject('读取失败');
      }
    });
  });
};

/**
 * 写文件操作
 * @param { String } url 存储文件路径
 * @returns
 */
module.exports.WriteFile = (url, data) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(url, JSON.stringify(data, null, 2), (error) => {
      if (!error) {
        resolve('写入成功');
      } else {
        reject('写入失败');
      }
    });
  });
};

module.exports.Success = (req, result) => {
  let resData = {
    status: 200,
    success: true,
    message: '操作成功',
    code: 'ok',
  };

  resData.data = result && result;

  return resData;

  // url: '/website?url=https://cn.chinadaily.com.cn',
  // method: 'GET',
  // headers:{}
  // baseUrl '/kleinblue-service',
  // originalUrl '/kleinblue-service/website?url=https://cn.chinadaily.com.cn',
  // params: {},
  // query: { url: 'https://cn.chinadaily.com.cn' },
  // body: {},
  // req.route.path   path: '/website',
};

module.exports.Error = (req, result) => {
  let resData = {
    status: 0,
    success: false,
    message: '操作失败',
    code: 'error',
  };

  resData.data = result && result;

  return resData;
};
